<script setup>
import { ElMessage, ElDrawer, ElMessageBox } from 'element-plus';
import { ref, getCurrentInstance, onMounted, reactive } from 'vue';
import dayjs from 'dayjs';
import api from '@/api'; // 统一导入 API

// 表单数据
const formInline = reactive({
    orderCode: '',
    dateRange: []
});

// API 请求配置
const config = reactive({
    page: 1,
    pageSize: 20,
    orderCode: '',
    beginTime: '',
    endTime: '',
    total: 0
});

// 订单数据
const orderData = ref([]);
const loading = ref(false);

// 订单详情
const orderDetails = ref(null);
const currentOrderId = ref(null); // 新增，用于保存当前订单 ID
const drawerVisible = ref(false);
const direction = ref('rtl');

const tableDetailsLabel = reactive([
    { prop: 'brand', label: '品牌' },
    { prop: 'productCode', label: '商品款号' },
    { prop: 'color', label: '颜色' },
    { prop: 'sizeType', label: '尺码类型' },
    { prop: 'actualSalePrice', label: '实销价' },
    { prop: 'retailPrice', label: '吊牌价' },
    { prop: 'discountAmount', label: '优惠金额' },
    { prop: 'createTime', label: '入库时间' }
]);

// 处理搜索
const handleSearch = () => {
  if (Array.isArray(formInline.dateRange) && formInline.dateRange.length === 2) {
    config.beginTime = formInline.dateRange[0] ? dayjs(formInline.dateRange[0]).format('YYYY-MM-DD 00:00:00') : '';
    config.endTime = formInline.dateRange[1] ? dayjs(formInline.dateRange[1]).format('YYYY-MM-DD 23:59:59') : '';
  } else {
    config.beginTime = '';
    config.endTime = '';
  }
  
  config.orderCode = typeof formInline.orderCode === 'string' ? formInline.orderCode.trim() : '';
  getOrderData();
};

// 获取订单数据
const getOrderData = async () => {
    loading.value = true;
    try {
        let data = await api.settlement.getOrderData(config);
        orderData.value = data.records.map(item => ({
            ...item,
            expanded: false
        }));
        config.total = data.total;
    } catch (error) {
        ElMessage.error('获取订单数据失败，请稍后再试');
    } finally {
        loading.value = false;
    }
};

// 获取订单详情
const getOrderDetails = async (id) => {
    try {
        let response = await api.settlement.getOrderDetails(id);
        orderDetails.value = response; // 假设 response.data 是产品详情数组
        console.log(orderDetails.value);
        drawerVisible.value = true;
    } catch (error) {
        ElMessage.error('获取订单详情失败，请稍后再试');
    }
};

// 删除订单
const handleDeleteOrder = (id) => {
    console.log(id);
    console.log(currentOrderId);
    ElMessageBox.confirm('确定要删除该订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await api.settlement.deleteOrder(id);
            ElMessage.success('删除成功');
            drawerVisible.value = false;
            getOrderData();
        } catch (error) {
            ElMessage.error('删除失败，请稍后再试');
        }
    }).catch(() => {
        // 取消删除
    });
};

// 分页处理
const handleSizeChange = (pageSize) => {
    config.pageSize = pageSize;
    getOrderData();
};
const handleCurrentChange = (page) => {
    config.page = page;
    getOrderData();
};

// 订单详情
const handleViewDetails = (order) => {
    currentOrderId.value = order.id // 设置当前订单 ID
    getOrderDetails(order.id)
}

onMounted(() => {
    getOrderData()
})
</script>

<template>
    <div class="Order-header">
        <el-form :inline="true" :model="formInline">
            <el-form-item label="订单编码:">
                <el-input v-model="formInline.orderCode" placeholder="请输入订单编码" @input="handleSearch"></el-input>
            </el-form-item>
            <el-form-item label="下单时间:">
                <el-date-picker v-model="formInline.dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleSearch" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
        </el-form>
    </div>
    
    <div class="Order-table">
        <el-table :data="orderData" v-loading="loading" style="width: 100%">
            <el-table-column label="订单编码" width="180">
                <template #default="scope">
                    <el-button type="text" @click="handleViewDetails(scope.row)">{{ scope.row.orderCode }}</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="total" label="件数" width="80" />
            <el-table-column prop="createUserName" label="处理人" width="150" />
            <el-table-column prop="createTime" label="处理时间" width="150" />
            <el-table-column prop="totalActualPrice" label="实付金额" width="150" />
            <el-table-column prop="totalRetailPrice" label="吊牌应付金额" width="150" />
            <el-table-column label="优惠" width="150">
                <template #default="scope">
                    {{ (scope.row.totalRetailPrice - scope.row.totalActualPrice).toFixed(2) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
                <template #default="scope">
                    <el-button type="text" @click="handleDeleteOrder(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    
    <el-drawer title="订单详情" v-model="drawerVisible" :direction="direction" size="70%">
        <div v-if="orderDetails">
            <div class="drawer-actions">
                <el-button type="danger" @click="handleDeleteOrder(currentOrderId)">删除订单</el-button>
            </div>
            <el-table :data="orderDetails" border style="width: 100%">
                <el-table-column v-for="column in tableDetailsLabel" :key="column.prop" :prop="column.prop" :label="column.label" :width="column.width">
                </el-table-column>
            </el-table>
        </div>
    </el-drawer>

    <el-pagination
        v-model:current-page="config.page"
        v-model:page-size="config.pageSize"
        :page-sizes="[20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="config.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
</template>

<style scoped>
.Order-header {
    display: flex;
    justify-content: space-between;
}

.Order-table {
    width: 100%;
}

.el-button {
    margin: 0;
}

.drawer-actions {
    text-align: right;
    margin-bottom: 20px;
}
</style>